package com.ghsc.ghxc.jsb.ui.integral.fragment

import android.graphics.Paint
import android.os.Bundle
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.KeyEvent
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.cn.appcore.base.BaseVMFragment
import com.cn.appcore.config.AppConfig
import com.cn.appcore.ext.loge
import com.cn.appcore.ext.setSingleClickListener
import com.cn.appcore.ext.showToast
import com.cn.appcore.ext.startKtxActivity
import com.cn.appcore.utils.GlideUtil
import com.cn.appcore.utils.GsonUtil
import com.cn.appcore.utils.KeyboardUtils
import com.cn.appcore.widget.CustomRefreshListener
import com.cn.appcore.widget.RefreshHelper
import com.ghsc.ghxc.jsb.R
import com.ghsc.ghxc.jsb.config.CustKey
import com.ghsc.ghxc.jsb.config.LoginHelper
import com.ghsc.ghxc.jsb.databinding.FragmentIntegralHomeBinding
import com.ghsc.ghxc.jsb.ui.home.activity.WebViewActivity
import com.ghsc.ghxc.jsb.ui.home.adapter.HomeIntegralBannerAdapter
import com.ghsc.ghxc.jsb.ui.integral.IntegralSupermarketViewModel
import com.ghsc.ghxc.jsb.ui.integral.activity.CommodityListActivity
import com.ghsc.ghxc.jsb.ui.integral.activity.IntegralGoodsDetailActivity
import com.ghsc.ghxc.jsb.ui.integral.adapter.IntegralCommodityAdapter
import com.ghsc.ghxc.jsb.ui.integral.bean.Category
import com.ghsc.ghxc.jsb.ui.integral.bean.HomeIntegralBean
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.youth.banner.indicator.RectangleIndicator

/**
 * 项目：GuoHuaJsb
 * 包名：com.ghsc.ghxc.jsb.ui.integral.fragment
 * 类名：IntegralSupermarketHomtFragment
 * 创建时间：2024/5/20 10:45
 * 创建人 @author： xiaolin
 * 描述 ：Todo... 积分首页
 */
class IntegralSupermarketHomeFragment : BaseVMFragment<IntegralSupermarketViewModel, FragmentIntegralHomeBinding>(R.layout.fragment_integral_home){
    override fun attachVMClass(): Class<IntegralSupermarketViewModel>? {
        return  IntegralSupermarketViewModel::class.java
    }

    override fun lazyLoad() {

    }
    // 商品列表
    //屏幕的宽度
    var widthPixels= AppConfig.getApplication().resources.displayMetrics.widthPixels
    //屏幕的密度
    var density= AppConfig.getApplication().resources.displayMetrics.density
    private val mAdapter: IntegralCommodityAdapter by lazy { IntegralCommodityAdapter((widthPixels/density)) }
    var mList = arrayListOf<HomeIntegralBean>()
    var keyword =""

    override fun initView(savedInstanceState: Bundle?) {
        binding.rvTypes.layoutManager = GridLayoutManager(requireActivity(),5)
        binding.rvTypes.adapter = typesAdapter
        //
        binding.rvList.layoutManager = StaggeredGridLayoutManager(2,
            StaggeredGridLayoutManager.VERTICAL)
        binding.rvList.adapter = mAdapter
        mAdapter.setNewInstance(mList)
        initRefreshLayout()
        //分类
        mViewModel.onCatecfgMethod("")
    }

    override fun initClickListener() {
        super.initClickListener()

        binding.tvBtnNext.setOnClickListener {
            keyword = binding.etSearch.text.toString().trim()
            if (!TextUtils.isEmpty(keyword)) {
                binding.etSearch.clearFocus()
                KeyboardUtils.hideKeyboard(binding.etSearch)
                pageNo = 1
                getListData()
            }else {
                keyword=""
                pageNo = 1
                getListData()
            }
        }

        binding.etSearch.setOnEditorActionListener(object : TextView.OnEditorActionListener {
            override fun onEditorAction(
                v: TextView,
                actionId: Int,
                event: KeyEvent?
            ): Boolean {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    // 先隐藏键盘
                    KeyboardUtils.hideKeyboard(v)
                    // 搜索，进行自己要的操作...
                    if (binding.etSearch.text.toString().trim().isNotEmpty()){
                        keyword = binding.etSearch.text.toString().trim()
                        pageNo = 1
                        getListData()
                    }else{
                        keyword =""
                        pageNo = 1
                        getListData()
                    }
                    return true
                }
                return false
            }
        })
        binding.etSearch.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }

            override fun afterTextChanged(p0: Editable?) {
                if(TextUtils.isEmpty(p0.toString().trim())){
                    keyword =""
                    pageNo = 1
                    getListData()
                }
            }

        })

        typesAdapter.setOnItemClickListener { adapter, view, position ->
            //跳转到商量列表
            startKtxActivity<CommodityListActivity>(
                values = arrayListOf(
                    "keyword" to typesAdapter.data[position].catename
                )
            )

        }
        mAdapter.setOnItemClickListener { adapter, view, position ->
            val bean = mAdapter.data[position]
            loge("position=item="+bean.toString())
            startKtxActivity<IntegralGoodsDetailActivity>(
                value =  "pid" to mAdapter.getItem(position).pid
            )
        }
    }
    private fun initRefreshLayout() {
        RefreshHelper.initRefreshLayout(binding.refreshLayout, object : CustomRefreshListener {
            override fun _onRefresh(refreshLayout: RefreshLayout?) {
                //分类
                mViewModel.onCatecfgMethod("")

            }

            override fun _onLoadMore(refreshLayout: RefreshLayout?) {
                pageNo++
                getListData()
            }
        })
    }
    fun getListData() {
        val map: HashMap<String, Any> = HashMap()
        map["keyword"] =keyword
        map["pindex"] =pageNo
        map["psize"] =20
        GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onMainIndexMethod(it1) }
    }



    override fun initRequestObserver() {
        super.initRequestObserver()
        mViewModel.apply {
            errorMsg.observe(this@IntegralSupermarketHomeFragment) {
                dismissLoading()
                RefreshHelper.finishRefresh(binding.refreshLayout, pageNo)
                showToast(it)
            }
            againLoginMsg.observe(this@IntegralSupermarketHomeFragment) {
                dismissLoading()
                RefreshHelper.finishRefresh(binding.refreshLayout, pageNo)
                showToast(CustKey.IN_AGAIN_MSG)
                LoginHelper.startLoginPage()

            }
            onCatecfgData.observe(this@IntegralSupermarketHomeFragment) {
                binding.banner.setAdapter(HomeIntegralBannerAdapter(it.data.data.lunbo))
                    .addBannerLifecycleObserver(this@IntegralSupermarketHomeFragment)
                    .indicator = RectangleIndicator(requireActivity())
                //分类
                typesAdapter.replaceData(it.data.data.category)
                pageNo = 1
                getListData()
                //分类
//                if (it.data.data.category.isNotEmpty())
//                    if (itemBen!=null)
//                        for ( i in it.data.data.category.indices)
//                            it.data.data.category[i].isSelect = it.data.data.category[i].catename ==itemBen!!.catename
//                XPopup.Builder(this@ReleaseCommodityActivity)
//                    .popupAnimation(PopupAnimation.ScaleAlphaFromCenter  )
//                    .customHostLifecycle(lifecycle)
//                    .dismissOnTouchOutside(true)
//                    .navigationBarColor(getCompatColor(R.color.bg_dark_color))
//                    .asCustom(
//                        IntegralTypeListPopupView(this@ReleaseCommodityActivity,
//                            it.data.data.category
//                        ) {
//                            loge("选择的是：${it.catename}")
//                            itemBen = it
//                            binding.etType.text = itemBen!!.catename
//                        }
//                    )
//                    .show()
            }
            onMainIndexData.observe(this@IntegralSupermarketHomeFragment){
                // 首页列表
                RefreshHelper.finishRefresh(binding.refreshLayout, pageNo)
                if (pageNo == 1) {
                    if (it.data.list.isNullOrEmpty()){
                        mAdapter.replaceData(it.data.list)
                    }
                    else {
                        mAdapter.replaceData(it.data.list)
                    }
                } else {
                    if (!it.data.list.isNullOrEmpty())
                        mAdapter.addData(it.data.list)
                }
            }
        }
    }
    private val typesAdapter by lazy { TypesAdapter() }
    inner class TypesAdapter  : BaseQuickAdapter<Category, BaseViewHolder>(
        R.layout.home_integral_type_item) {
        override fun convert(helper: BaseViewHolder, item: Category) {
            GlideUtil.ImageLoad(this.context,item.cateimg,helper.getView(R.id.imgIcon))
            helper
                .setText(R.id.tvMenu, item.catename)
        }
    }

}